<template>
  <div class="driver-form-page">
    <div class="page-header-fixed">
      <div class="header-left">
        <a class="back-link" @click="handleBack">
          <ArrowLeftOutlined />
          <span>返回司机列表</span>
        </a>
        <h2>{{ isEdit ? '编辑司机' : '新增司机' }}</h2>
      </div>
      <div class="header-actions">
        <a-space>
          <a-button @click="handleBack">取消</a-button>
          <a-button type="primary" :loading="submitting" @click="handleSubmit">
            保存
          </a-button>
        </a-space>
      </div>
    </div>
    
    <div class="page-content">
      <a-card class="form-card">
        <a-form ref="formRef" :model="formData" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
          <!-- 基本信息 -->
          <div class="form-section">
            <div class="section-header">
              <span class="section-title">基本信息</span>
            </div>
            
            <a-form-item label="姓名" name="name">
              <a-input v-model:value="formData.name" placeholder="请输入姓名" />
            </a-form-item>
            
            <a-form-item label="性别">
              <a-radio-group v-model:value="formData.gender">
                <a-radio :value="1">男</a-radio>
                <a-radio :value="2">女</a-radio>
              </a-radio-group>
            </a-form-item>
            
            <a-form-item label="联系电话" name="phone">
              <a-input v-model:value="formData.phone" placeholder="请输入手机号" />
            </a-form-item>
            
            <a-form-item label="身份证号" name="idCard">
              <a-input v-model:value="formData.idCard" placeholder="请输入18位身份证号" />
            </a-form-item>
          </div>
          
          <!-- 驾驶证信息 -->
          <div class="form-section">
            <div class="section-header">
              <span class="section-title">驾驶证信息</span>
            </div>
            
            <a-form-item label="驾驶证类型" name="licenseType">
              <a-select v-model:value="formData.licenseType" placeholder="请选择驾驶证类型">
                <a-select-option value="C1">C1</a-select-option>
                <a-select-option value="C2">C2</a-select-option>
                <a-select-option value="B1">B1</a-select-option>
                <a-select-option value="B2">B2</a-select-option>
                <a-select-option value="A1">A1</a-select-option>
                <a-select-option value="A2">A2</a-select-option>
                <a-select-option value="A3">A3</a-select-option>
              </a-select>
            </a-form-item>
            
            <a-form-item label="驾驶证号" name="licenseNo">
              <a-input v-model:value="formData.licenseNo" placeholder="请输入驾驶证号" />
            </a-form-item>
            
            <a-form-item label="驾驶证到期" name="licenseExpireDate">
              <a-date-picker
                v-model:value="formData.licenseExpireDate"
                format="YYYY-MM-DD"
                style="width: 100%"
                placeholder="请选择到期日期"
              />
            </a-form-item>
          </div>
          
          <!-- 工作信息 -->
          <div class="form-section">
            <div class="section-header">
              <span class="section-title">工作信息</span>
            </div>
            
            <a-form-item label="入职日期" name="entryDate">
              <a-date-picker
                v-model:value="formData.entryDate"
                format="YYYY-MM-DD"
                style="width: 100%"
                placeholder="请选择入职日期"
              />
            </a-form-item>
            
            <a-form-item label="紧急联系人">
              <a-input v-model:value="formData.emergencyContact" placeholder="请输入紧急联系人" />
            </a-form-item>
            
            <a-form-item label="紧急联系电话">
              <a-input v-model:value="formData.emergencyPhone" placeholder="请输入紧急联系电话" />
            </a-form-item>
          </div>
          
          <!-- 站点信息 -->
          <div class="form-section" v-if="shouldShowSiteInfo">
            <div class="section-header">
              <span class="section-title">站点信息</span>
            </div>
            
            <a-form-item label="所属站点" name="siteId">
              <a-select
                v-model:value="formData.siteId"
                placeholder="请选择站点"
                style="width: 100%"
                :loading="loadingSites"
              >
                <a-select-option 
                  v-for="site in siteOptions" 
                  :key="site.id" 
                  :value="site.id"
                >
                  {{ site.siteName }}（{{ site.siteCode }}）
                </a-select-option>
              </a-select>
              <div class="form-item-tip">普通用户自动使用当前站点</div>
            </a-form-item>
          </div>
          
          <!-- 其他信息 -->
          <div class="form-section">
            <div class="section-title">其他信息</div>
            
            <a-form-item label="司机状态">
              <a-radio-group v-model:value="formData.driverStatus">
                <a-radio v-for="item in driverStatuses" :key="item.dictCode" :value="item.dictCode">
                  {{ item.dictLabel }}
                </a-radio>
              </a-radio-group>
            </a-form-item>
            
            <a-form-item label="备注">
              <a-textarea v-model:value="formData.remark" :rows="3" :maxlength="500" show-count />
            </a-form-item>
          </div>
          
          <a-form-item :wrapper-col="{ offset: 6, span: 16 }">
            <a-space size="large">
              <a-button type="primary" :loading="submitting" @click="handleSubmit">
                {{ isEdit ? '保存修改' : '保存司机' }}
              </a-button>
              <a-button @click="handleBack">取消</a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import { createDriver, updateDriver, getDriverById } from '@/api/tenant/driver'
import { getSiteList } from '@/api/tenant/site'
import { getDictionaryByType } from '@/api/tenant/dictionary'
import { useUserStore } from '@/stores/user'
import type { DriverFormData } from '@/types/driver'
import type { Site } from '@/types/site'
import type { Dictionary } from '@/types/dictionary'
import type { Dayjs } from 'dayjs'
import dayjs from 'dayjs'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const isEdit = computed(() => route.name === 'DriverEdit')

// 判断是否需要显示站点信息
// 超级管理员在全部站点模式下可以选择站点
const shouldShowSiteInfo = computed(() => {
  const isSuperAdmin = userStore.userInfo?.role === 'SUPER_ADMIN'
  const isViewingAllSites = userStore.userInfo?.siteId === null
  return isSuperAdmin && isViewingAllSites
})

const formData = reactive<Omit<DriverFormData, 'licenseExpireDate' | 'entryDate'> & {
  licenseExpireDate?: Dayjs
  entryDate?: Dayjs
  siteId?: number
}>({
  name: '',
  gender: 1,
  phone: '',
  idCard: '',
  licenseType: 'C1',
  licenseNo: '',
  licenseExpireDate: undefined,
  entryDate: undefined,
  emergencyContact: '',
  emergencyPhone: '',
  driverStatus: 'IDLE',
  remark: '',
  siteId: undefined,
})

// 站点列表
const siteOptions = ref<Site[]>([])
const loadingSites = ref(false)

// 字典数据
const driverStatuses = ref<Dictionary[]>([])

// 获取站点列表
const fetchSites = async () => {
  if (!shouldShowSiteInfo.value) return
  
  loadingSites.value = true
  try {
    const response = await getSiteList()
    const data = response.data as any
    siteOptions.value = (data || []) as Site[]
  } catch (error) {
    console.error('获取站点列表失败:', error)
  } finally {
    loadingSites.value = false
  }
}

const rules = {
  name: [{ required: true, message: '请输入姓名' }],
  phone: [
    { required: true, message: '请输入联系电话' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
  ],
  idCard: [
    { required: true, message: '请输入身份证号' },
    { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的身份证号' },
  ],
  licenseType: [{ required: true, message: '请选择驾驶证类型' }],
  licenseNo: [{ required: true, message: '请输入驾驶证号' }],
  licenseExpireDate: [{ required: true, message: '请选择驾驶证到期日期' }],
  entryDate: [{ required: true, message: '请选择入职日期' }],
}

const formRef = ref()
const submitting = ref(false)

const fetchDriverDetail = async () => {
  const id = Number(route.params.id)
  if (!id) return
  
  try {
    const response = await getDriverById(id)
    const driver = response.data as any
    
    Object.assign(formData, {
      ...driver,
      licenseExpireDate: driver.licenseExpireDate ? dayjs(driver.licenseExpireDate) : undefined,
      entryDate: driver.entryDate ? dayjs(driver.entryDate) : undefined,
      siteId: driver.siteId,
    })
  } catch (error: any) {
    console.error('获取司机详情失败:', error)
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    const submitData: any = {
      name: formData.name,
      gender: formData.gender,
      phone: formData.phone,
      idCard: formData.idCard,
      licenseType: formData.licenseType,
      licenseNo: formData.licenseNo,
      licenseExpireDate: formData.licenseExpireDate!.format('YYYY-MM-DD'),
      entryDate: formData.entryDate!.format('YYYY-MM-DD'),
      emergencyContact: formData.emergencyContact,
      emergencyPhone: formData.emergencyPhone,
      driverStatus: formData.driverStatus,
      remark: formData.remark,
      // 站点ID（超级管理员在全部站点模式下可指定，其他用户自动使用当前站点）
      siteId: shouldShowSiteInfo.value ? formData.siteId : undefined,
    }
    
    if (isEdit.value) {
      await updateDriver(Number(route.params.id), submitData)
      message.success('司机更新成功')
    } else {
      await createDriver(submitData)
      message.success('司机创建成功')
    }
    
    router.push('/tenant/driver')
  } catch (error: any) {
    console.error('保存司机失败:', error)
    if (error.message && error.message !== 'Error') {
      message.error(error.message)
    }
  } finally {
    submitting.value = false
  }
}

const handleBack = () => {
  router.push('/tenant/driver')
}

// 加载字典数据
const loadDictionaries = async () => {
  try {
    const response = await getDictionaryByType('DRIVER_STATUS')
    driverStatuses.value = (response.data || []) as unknown as Dictionary[]
  } catch (error) {
    console.error('加载字典失败:', error)
  }
}

onMounted(() => {
  loadDictionaries()
  fetchSites()
  if (isEdit.value) {
    fetchDriverDetail()
  }
})
</script>

<style scoped>
.driver-form-page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.page-header-fixed {
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background: #fff;
  padding-bottom: 16px;
  margin-bottom: 16px;
  border-bottom: 1px solid var(--border-color);
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.back-link {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: color var(--transition-fast);
}

.back-link:hover {
  color: var(--primary-color);
}

.page-header-fixed h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-content {
  flex: 1;
  overflow: auto;
  padding: 0 16px 16px;
}

.form-card {
  max-width: 960px;
  border: none;
  box-shadow: var(--shadow-card);
}

::deep(.form-card .ant-card-body) {
  padding: 28px;
}

.form-section {
  margin-bottom: 32px;
}

.form-section:last-of-type {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.section-title {
  position: relative;
  padding-left: 12px;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 2px;
  bottom: 2px;
  width: 4px;
  border-radius: 4px;
  background: var(--primary-color);
}

::deep(.ant-form-item) {
  margin-bottom: 20px;
}

::deep(.ant-form-item-label > label) {
  font-weight: 500;
  color: var(--text-primary);
}

@media (max-width: 992px) {
  .page-header-fixed {
    flex-direction: column;
    gap: 12px;
  }

  .header-actions {
    align-self: flex-end;
  }
}
</style>

